package com.example.status;

import com.example.bean.WaterSenSorFunction;
import com.example.bean.WaterSensor;
import com.sun.xml.internal.bind.v2.TODO;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * ClassName: KeyedListStatusDemo
 * Package: com.example.status
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-21
 * Time: 16:12
 */


// Map状态
public class KeyedAggregatingStateDemo {
    public static void main(String[] args) throws Exception {

        //1.创建执行环境

        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> dataTime = env.socketTextStream("hadoop103", 7777)
                //读进来之后 map算子转换
                .map(new WaterSenSorFunction())
                //生成水位线
                //assign 分配  Timestamps时间戳 和 水位线
                //这个方法的参数是 WatermarkStrategy(接口) 水位线生成策略
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                //方法前面 加一个泛型？？
                                //指定 水位线是单调升序  还是乱序
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3)) //表示乱序 最大诚信3秒
                                //从数据中提取事件时间 withTimestampAssigner (带有时间戳的生成器)
                                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                                    @Override
                                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                        //获取数据的时间戳 单位是毫秒
                                        return element.getTs() * 1000L;
                                    }
                                })
                );


        //统计每种传感器每种水位值出现的次数。
        dataTime.keyBy(value -> value.getId())
                //需求 计算每种传感器的平均水位
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    //创建Aggregating状态
                    AggregatingState<Integer, Double> vcAgg;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //状态初始花
                        vcAgg = getRuntimeContext().getAggregatingState(
                                new AggregatingStateDescriptor<Integer, Tuple2<Integer, Integer>, Double>(
                                        "vcAgg",
                                        new AggregateFunction<Integer, Tuple2<Integer, Integer>, Double>() {
                                            @Override
                                            public Tuple2<Integer, Integer> createAccumulator() {
                                                //初始化数据
                                                return Tuple2.of(0, 0);
                                            }
                                            @Override
                                            public Tuple2<Integer, Integer> add(Integer value, Tuple2<Integer, Integer> accumulator) {
                                                return Tuple2.of(accumulator.f0 + value, accumulator.f1 + 1);
                                            }
                                            @Override
                                            public Double getResult(Tuple2<Integer, Integer> accumulator) {
                                                //返回的结果
                                                return accumulator.f0 * 1.0 / accumulator.f1;
                                            }
                                            @Override
                                            public Tuple2<Integer, Integer> merge(Tuple2<Integer, Integer> a, Tuple2<Integer, Integer> b) {
                                                //用到会话窗口使用
                                                return null;
                                            }
                                        },
                                        Types.TUPLE(Types.INT, Types.INT) //这个类型 只用是计算数值的类型
                                )
                        );
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        //将水位值 添加到聚合状态
                        vcAgg.add(value.getVc());
                        //从聚合状态 获取结果值
                        Double aDouble = vcAgg.get();

                        out.collect("传感器ID为" + value.getId() + ",平均水位值= " + aDouble);
                    }
                }).print();


        env.execute();
    }
}
